package com.sqx.modules.health.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sqx.modules.health.common.Constants;
import com.sqx.modules.health.common.Result;
import com.sqx.modules.health.entity.*;
import com.sqx.modules.health.service.*;
import com.sqx.modules.health.utils.ExcelImportUtil;
import com.sqx.modules.health.utils.HttpUtils;
import com.sqx.modules.health.utils.MyBeanUtil;
import com.sqx.modules.health.utils.StringUtil;
import com.sqx.modules.health.vo.NcgDeviceWatchVO;
import com.sqx.modules.health.vo.NcgWatchVO;
import com.sqx.modules.sys.entity.SysUserEntity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 * 智能手表设备表 前端控制器
 * </p>
 *
 * @author gxy
 * @since 2022-04-21
 */

@Api(value = "智能手表设备表", tags = "", description = "")
@RestController
@RequestMapping("/health/ncgDeviceWatch")
public class NcgDevice_WatchController {
    @Autowired
    private INcgDeviceWatchService ncgDeviceWatchService;
    @Autowired
    private IHospitalService hospitalService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IAgentService agentService;
    @Autowired
    private NcgWatchService watchService;
    @Autowired
    private IReceiveService receiveService;
    @Autowired
    private IAppProductService productService;
    @Autowired
    private IDepartmentService departmentService;

    // 新增或更新
    @PostMapping("/save")
    @ApiOperation(value = "新增或更新智能手表设备表", notes = "新增或更新智能手表设备表")
    public Result save(@RequestBody NcgDeviceWatch ncgDeviceWatch) {
        // 新增操作
        if (ObjectUtil.isEmpty(ncgDeviceWatch.getId())) {
            // 生成UUID
            ncgDeviceWatch.setUuid(UUID.randomUUID().toString().replaceAll("-", ""));
            // 设置创建时间为当前时间
            ncgDeviceWatch.setCreatetime(LocalDateTime.now());
            // 设置删除状态为 未删除
            ncgDeviceWatch.setIsdelete(0);
            ncgDeviceWatch.setIsenable(0);
            // 设备类型为手表
            ncgDeviceWatch.setType("1");
        } else {
            ncgDeviceWatch.setUpdatetime(LocalDateTime.now());
            QueryWrapper<NcgDeviceWatch> wrapper = new QueryWrapper<NcgDeviceWatch>()
                    .eq(ObjectUtil.isNotEmpty(ncgDeviceWatch.getDevicename()), "devicename", ncgDeviceWatch.getDevicename())
                    .eq(ObjectUtil.isNotEmpty(ncgDeviceWatch.getHid()), "hid", ncgDeviceWatch.getHid());
            List<NcgDeviceWatch> watches = ncgDeviceWatchService.list(wrapper);
            if (CollectionUtils.isNotEmpty(watches)) {
                return Result.error(Constants.CODE_500, "该设备名称已存在！");
            }
        }
        return Result.success(ncgDeviceWatchService.saveOrUpdate(ncgDeviceWatch));
    }

    // 根据ID删除
    @GetMapping("/del/{id}")
    @ApiOperation(value = "根据ID删除智能手表设备表", notes = "根据ID删除智能手表设备表")
    public Result delete(@PathVariable Integer id) {
        return Result.success(ncgDeviceWatchService.removeById(id));
    }

    // 根据IDS删除
    @GetMapping("/del/batch")
    @ApiOperation(value = "根据IDS删除智能手表设备表", notes = "根据IDS删除智能手表设备表")
    public Result deleteBatch(@RequestParam List<Integer> ids) {
        return Result.success(ncgDeviceWatchService.removeByIds(ids));
    }

    // 查询全部
    @GetMapping("/findAll")
    @ApiOperation(value = "查询全部智能手表设备表", notes = "查询全部智能手表设备表")
    public Result findAll() {
        return Result.success(ncgDeviceWatchService.list());
    }

    // 根据ID查询一条记录
    @GetMapping("/findOne")
    @ApiOperation(value = "根据ID查询一条记录智能手表设备表", notes = "根据ID查询一条记录智能手表设备表")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(ncgDeviceWatchService.getById(id));
    }

    // 分页查询
    @GetMapping("/findPage")
    @ApiOperation(value = "分页查询智能手表设备表", notes = "分页查询智能手表设备表")
    public Result findPage(@RequestParam Integer pageNum,
                           @RequestParam Integer pageSize,
                           @RequestParam(required = false, defaultValue = "") Long loginHid,
                           @RequestParam(required = false, defaultValue = "") String imei,
                           @RequestParam(required = false, defaultValue = "") Integer hid) {
        QueryWrapper<NcgDeviceWatch> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(imei), "imei", imei);
        // 当前登录人去查询数据 (医院管理员只能查看自己医院的数据)
        if (ObjectUtil.isNotEmpty(loginHid)) {
            queryWrapper.eq("hid", loginHid);
        }
        if (ObjectUtil.isNotEmpty(hid)) {
            queryWrapper.eq("hid", hid);
        }
//        queryWrapper.eq("type", 1);
        queryWrapper.orderByDesc("createtime");
        Page<NcgDeviceWatch> page = ncgDeviceWatchService.page(new Page<>(pageNum, pageSize), queryWrapper);
        List<NcgDeviceWatchVO> ncgDeviceWatchVOS = MyBeanUtil.collectionCopy(page.getRecords(), NcgDeviceWatchVO.class);
        Page<NcgDeviceWatchVO> result = new Page<>();
        // 将查询到的数据赋值到返回数据中
        result.setRecords(ncgDeviceWatchVOS);
        result.setTotal(page.getTotal());
        for (NcgDeviceWatchVO device : result.getRecords()) {
            if (ObjectUtil.isNotEmpty(device.getHid())) {
                Hospital hospital = hospitalService.getById(device.getHid());
                // 获取医院名称
                if (!ObjectUtil.isEmpty(hospital)) {
                    device.setHName(ObjectUtil.isEmpty(hospital.getName()) ? hospital.getAbbreviation() : hospital.getName());
                }
            }

            if (ObjectUtil.isNotEmpty(device.getUid())) {
                SysUserEntity user = userService.getRedisByUid(device.getUid());
                if(ObjectUtil.isNull(user)) {
                    device.setUName("无佩戴者");
                } else {
                    device.setUName(ObjectUtil.isEmpty(user.getNickName()) ? user.getUsername() : user.getNickName());
                }
            }

            if (device.getAgentid() != null) {
                Agent agent = agentService.getById(device.getAgentid());
                device.setAgentName(ObjectUtil.isEmpty(agent.getName()) ? agent.getAbbreviation() : agent.getName());
            }
            if (ObjectUtil.isNotEmpty(device.getDoctorid())) {
                SysUserEntity user = userService.getRedisByUid(device.getDoctorid());
                device.setDoctorName(user.getNickName());
            }
            if (ObjectUtil.isNotEmpty(device.getStatus())) {
                if(device.getStatus() == 2) {
                    device.setStatusName("使用中");
                }else if(device.getStatus() == 3) {
                    device.setStatusName("空闲中");
                }else{

                }
            }
            if (ObjectUtil.isNotEmpty(device.getProductid())) {
                AppProduct product = productService.getById(device.getProductid());
                device.setProductName(product.getName());
            }
            if (ObjectUtil.isNotEmpty(device.getDepartmentid())) {
                Department department = departmentService.getById(device.getDepartmentid());
                device.setDepartmentName(department.getName());
            }
        }
        return Result.success(result);
    }

    /**
     * 设备绑定用户
     *
     * @param params
     * @return
     */
    @GetMapping("/binding")
    public Result binding(@RequestParam Map<String, String> params) {
        Integer status = 3; // 修改状态为 用户绑定状态
        Integer num = hospitalService.binding(params.get("id"), params.get("uid"), status);
        // 绑定用户的同时将数据保存到用户设备表
        Integer saveNum = hospitalService.saveUserDevice(params.get("id"), params.get("uid"));
        if (num != 0 && saveNum != 0) {
            return Result.success("绑定成功");
        }
        return Result.error(Constants.CODE_500, "绑定失败");
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "doctorid", value = "医生id", paramType = "Long"),
            @ApiImplicitParam(name = "id", value = "设备id", paramType = "Long"),
    })
    @GetMapping("/bindingDoctor")
    public Result bindingDoctor(@RequestParam Map<String, String> params) {
        LambdaUpdateWrapper<NcgDeviceWatch> updateWrapper = new LambdaUpdateWrapper<NcgDeviceWatch>()
                .set(NcgDeviceWatch::getDoctorid, params.get("doctorid"))
                .set(NcgDeviceWatch::getStatus, 3)
                .eq(NcgDeviceWatch::getId, params.get("id"));
        if (ncgDeviceWatchService.update(updateWrapper)) {
            return Result.success("success");
        } else {
            return Result.error(Constants.CODE_500, "error");
        }
    }

    @GetMapping("/getDeviceByHid")
    public Result getDeviceByHid(@RequestParam Long hid, @RequestParam(required = false, defaultValue = "") Integer type) {
//        if (type == 5) {
//            //走生化科血糖
//            QueryWrapper<NcgDeviceWatch> wrapper = new QueryWrapper<NcgDeviceWatch>()
//                    .eq(ObjectUtil.isNotEmpty(hid), "hid", hid)
//                    .eq("type",3)
//                    .eq("departmentid",2)
//                    .ne("status", 2);
//            return Result.success(ncgDeviceWatchService.list(wrapper));
//        }else {
            QueryWrapper<NcgDeviceWatch> wrapper = new QueryWrapper<NcgDeviceWatch>()
                    .eq(ObjectUtil.isNotEmpty(hid), "hid", hid)
                    .eq(ObjectUtil.isNotEmpty(type), "type", type)
//                    .eq("departmentid",1)
                    .ne("status", 2);
            return Result.success(ncgDeviceWatchService.list(wrapper));
//        }
    }


    @GetMapping("/getDeviceUseByDocid")
    public Result getDeviceUseByDocid(@RequestParam Integer pageNum,@RequestParam Integer pageSize,
                                    @RequestParam(required = false,defaultValue = "")Long docid) {

//            QueryWrapper<NcgDeviceWatch> wrapper = new QueryWrapper<NcgDeviceWatch>()
//                    .eq(ObjectUtil.isNotEmpty(docid), "doctorid", 0);
//        Page<NcgDeviceWatch> result = ncgDeviceWatchService.page(new Page<>(pageNum, pageSize), wrapper);
//        User users = userService.getById(docid);
//        List<NcgDeviceWatch>  aa =  ncgDeviceWatchService.getDeviceHid(users.getHid());
//        aa.forEach(one -> {
//            if (ObjectUtil.isNotEmpty(one.getUid())) {
//                User user = userService.getById(one.getUid());
//                if(ObjectUtil.isNull(user))one.setUName("患者信息有误");
//                one.setUName(ObjectUtil.isEmpty(user.getNickName()) ? user.getUsername() : user.getNickName());
//            }
//            if (ObjectUtil.isNotEmpty(one.getDoctorid())) {
//                User user = userService.getById(one.getDoctorid());
//                if(ObjectUtil.isNull(user))one.setUName("患者信息有误");
//                one.setDocName(ObjectUtil.isEmpty(user.getNickName()) ? user.getUsername() : user.getNickName());
//            }
//        });
//        result.setRecords(aa);
//        result.setTotal(aa.size());
//
//        return  Result.success(result);

        SysUserEntity users = userService.getById(docid);
        List<NcgDeviceWatch>  deviceList =  ncgDeviceWatchService.getDeviceHid(users.getHid());
//        Page<NcgDeviceWatch> page = ncgDeviceWatchService.page(new Page<>(pageNum, pageSize), wrapper);
        List<NcgDeviceWatchVO> ncgDeviceWatchVOS = MyBeanUtil.collectionCopy(deviceList, NcgDeviceWatchVO.class);
        Page<NcgDeviceWatchVO> result = new Page<>();
        // 将查询到的数据赋值到返回数据中
        result.setRecords(ncgDeviceWatchVOS);
        result.setTotal(deviceList.size());
        for (NcgDeviceWatchVO device : result.getRecords()) {
            if (ObjectUtil.isNotEmpty(device.getHid())) {
                Hospital hospital = hospitalService.getById(device.getHid());
                // 获取医院名称
                if (!ObjectUtil.isEmpty(hospital)) {
                    device.setHName(ObjectUtil.isEmpty(hospital.getName()) ? hospital.getAbbreviation() : hospital.getName());
                }
            }

            if (ObjectUtil.isNotEmpty(device.getUid())) {
                SysUserEntity user = userService.getRedisByUid(device.getUid());
                if(ObjectUtil.isNull(user))device.setUName("无佩戴者");
                device.setUName(ObjectUtil.isEmpty(user.getNickName()) ? user.getUsername() : user.getNickName());
            }

            if (device.getAgentid() != null) {
                Agent agent = agentService.getById(device.getAgentid());
                device.setAgentName(ObjectUtil.isEmpty(agent.getName()) ? agent.getAbbreviation() : agent.getName());
            }
            if (ObjectUtil.isNotEmpty(device.getDoctorid())) {
                SysUserEntity user = userService.getRedisByUid(device.getDoctorid());
                device.setDoctorName(user.getNickName());
            }
            if (ObjectUtil.isNotEmpty(device.getStatus())) {
                if(device.getStatus() == 2) {
                    device.setStatusName("使用中");
                }else if(device.getStatus() == 3) {
                    device.setStatusName("空闲中");
                }else{

                }
            }
            if (ObjectUtil.isNotEmpty(device.getProductid())) {
                AppProduct product = productService.getById(device.getProductid());
                device.setProductName(product.getName());
            }
            if (ObjectUtil.isNotEmpty(device.getDepartmentid())) {
                Department department = departmentService.getById(device.getDepartmentid());
                device.setDepartmentName(department.getName());
            }
        }
        return Result.success(result);

    }

    /**
     * 设备解绑
     *
     * @param id  设备ID
     * @return
     */
    @GetMapping("/unBinding")
    public Result unBinding(@RequestParam("id") String id) {

        try {
            Integer status = 3; // 修改状态为 用户解绑

            Integer num = hospitalService.unBinding(id, status);
            if (ObjectUtil.notEqual(num, 1)) {

                return Result.error(Constants.CODE_500, "解绑失败");
            }
            return Result.success("解绑成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(Constants.CODE_500, "解绑失败");
        }
    }


    @Transactional
    @PostMapping("/insertBath")
    public Result insertBath(MultipartFile file, @RequestParam(required = false, defaultValue = "") Long hid) {
        if (hid != null) {
            return insertBathByHospital(file, hid);
        } else {
            return insertBath(file);
        }
    }


    private Result insertBathByHospital(MultipartFile file, Long hid) {
        NcgDeviceWatchVO vo = new NcgDeviceWatchVO();

        NcgDeviceWatch ncgDeviceWatch = new NcgDeviceWatch();

        // 解析Excel
        List<List<String>> lists = ExcelImportUtil.importExcel(file);
        if (lists.size() == 0) {
            return Result.error(Constants.CODE_500, "导入失败,请检查文件!!!");
        }
        int succ = 0;
        List<Integer> errLine = new ArrayList<>();

        try {
            for (int i = 0; i < lists.size(); i++) {
                // 设备编码
                vo.setImei(lists.get(i).get(0));
                // 设备状态
                switch (lists.get(i).get(1)) {
                    case "平台库存":
                        vo.setStatus(0);
                        break;
                    case "医院库存":
                        vo.setStatus(1);
                        break;
                    case "用户解绑":
                        vo.setStatus(2);
                        break;
                    case "用户绑定":
                        vo.setStatus(3);
                        break;
                    case "医护领用":
                        vo.setStatus(4);
                        break;
                    case "报修":
                        vo.setStatus(5);
                        break;
                    case "平台报修":
                        vo.setStatus(6);
                        break;
                    case "平台报废":
                        vo.setStatus(7);
                        break;
                    default:
                        vo.setStatus(0);
                        break;
                }
                // 定位周期
                vo.setCycle(Integer.parseInt(lists.get(i).get(2)));

                // 设置医院ID为当前发送的医院id
                vo.setHid(hid);
                // 生成UUID 设置创建时间 删除状态 启用状态
                vo.setUuid(UUID.randomUUID().toString().replaceAll("-", ""));
                vo.setCreatetime(LocalDateTime.now());
                vo.setIsdelete(0);
                vo.setIsenable(1);
                vo.setId(null);
                BeanUtil.copyProperties(vo, ncgDeviceWatch);
                ncgDeviceWatchService.save(ncgDeviceWatch);
                succ += 1;
            }
            return Result.success("成功导入" + succ + "条,失败" + errLine.size() + "条,在" + errLine + "行");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(Constants.CODE_500, "导入失败!!!");
        }
    }

    private Result insertBath(MultipartFile file) {
        NcgDeviceWatchVO vo = new NcgDeviceWatchVO();

        NcgDeviceWatch ncgDeviceWatch = new NcgDeviceWatch();

        // 解析Excel
        List<List<String>> lists = ExcelImportUtil.importExcel(file);
        if (lists.size() == 0) {
            return Result.error(Constants.CODE_500, "导入失败,请检查文件!!!");
        }
        int succ = 0;
        List<Integer> errLine = new ArrayList<>();

        try {
            for (int i = 0; i < lists.size(); i++) {
                // 设备编码
                vo.setImei(lists.get(i).get(0));
                // 所属医院
                if (getHospitalId(lists.get(i).get(1)) == null) {
                    errLine.add(i + 1);
                    continue;
                } else {
                    // 将医院id 设置值
                    vo.setHid(getHospitalId(lists.get(i).get(1)));
                }
                // 设备状态
                switch (lists.get(i).get(2)) {
                    case "平台库存":
                        vo.setStatus(0);
                        break;
                    case "医院库存":
                        vo.setStatus(1);
                        break;
                    case "用户解绑":
                        vo.setStatus(2);
                        break;
                    case "用户绑定":
                        vo.setStatus(3);
                        break;
                    case "医护领用":
                        vo.setStatus(4);
                        break;
                    case "报修":
                        vo.setStatus(5);
                        break;
                    case "平台报修":
                        vo.setStatus(6);
                        break;
                    case "平台报废":
                        vo.setStatus(7);
                        break;
                    default:
                        vo.setStatus(0);
                        break;
                }
                // 定位周期
                vo.setCycle(Integer.parseInt(lists.get(i).get(3)));

                // 生成UUID 设置创建时间 删除状态 启用状态
                vo.setUuid(UUID.randomUUID().toString().replaceAll("-", ""));
                vo.setCreatetime(LocalDateTime.now());
                vo.setIsdelete(0);
                vo.setIsenable(1);
                vo.setId(null);
                vo.setType("1");
                BeanUtil.copyProperties(vo, ncgDeviceWatch);
                ncgDeviceWatchService.save(ncgDeviceWatch);
                succ += 1;
            }
            return Result.success("成功导入" + succ + "条,失败" + errLine.size() + "条,在" + errLine + "行");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(Constants.CODE_500, "导入失败!!!");
        }
    }

    private Long getHospitalId(String hospitalName) {
        return hospitalService.getHospitalId(hospitalName);
    }

    @GetMapping("/getAllHospitalDevice")
    public Result getAllHospitalDevice(@RequestParam(required = false, defaultValue = "") Long hid) {
        // 查询出当前医院所有可用的设备(未绑定用户 切 没有报修等状态)
        return Result.success(ncgDeviceWatchService.getAllHospitalDevice(hid));
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "hid", value = "医院id", paramType = "Long"),
            @ApiImplicitParam(name = "type", value = "设备类型 => 1. 手表 2. 血压计 3. 血糖血压仪 4. 心电", paramType = "Integer"),
            @ApiImplicitParam(name = "startTime", value = "开始时间", paramType = "String"),
            @ApiImplicitParam(name = "endTime", value = "结束时间", paramType = "String"),
            @ApiImplicitParam(name = "deviceType", value = "测量类型 ==> 针对血糖血压仪    01 血压数据  02 血糖数据", paramType = "String"),
    })
    @GetMapping("/measurementRecord")
    public Result measurementRecord(@RequestParam(required = false, defaultValue = "") Integer type,
                                    @RequestParam(required = false, defaultValue = "") Long hid,
                                    @RequestParam(required = false, defaultValue = "") String startTime,
                                    @RequestParam(required = false, defaultValue = "") String endTime,
                                    @RequestParam(required = false, defaultValue = "") String deviceType) {

        if (ObjectUtil.isEmpty(type)) {
            return Result.error(Constants.CODE_500, "参数错误!!");
        }

        List<JSONObject> imeiList = ncgDeviceWatchService.getDeviceImei(type, hid);

        if (CollectionUtils.isEmpty(imeiList)) {
            return Result.error(Constants.CODE_500, "未找到设备!!");
        }

        List<String> iemi = new ArrayList<>();

        for (JSONObject jsonObject : imeiList) {
            iemi.add(StringUtil.toString(jsonObject.get("imei")));
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        // 默认查截止到目前的今天数据
        if (StringUtils.isBlank(startTime)) {
            DateTime dateTime = DateUtil.beginOfDay(new Date());
            startTime = dateTime.toString();
        } else {
            DateUtil.parse(startTime, "yyyy-MM-dd HH:mm:ss");
        }

        if (StringUtils.isBlank(endTime)) {
            endTime = DateUtil.date().toString();
        } else {
            DateUtil.parse(endTime, "yyyy-MM-dd HH:mm:ss");
        }

        if (ObjectUtil.equals(type, 1)) {
            QueryWrapper<NcgWatch> wrapper = new QueryWrapper<NcgWatch>()
                    .in(CollectionUtils.isNotEmpty(iemi), "imei", iemi).
                    between(ObjectUtil.isNotEmpty(startTime) && ObjectUtil.isNotEmpty(endTime), "createtime", startTime, endTime);
            List<NcgWatchVO> ncgWatchVO = MyBeanUtil.collectionCopy(watchService.list(wrapper), NcgWatchVO.class);
            for (JSONObject jsonObject : imeiList) {
                for (NcgWatchVO ncgWatch : ncgWatchVO) {
                    if (ObjectUtil.equals(jsonObject.get("imei"), ncgWatch.getImei())) {
                        SysUserEntity user = userService.getRedisByUid(jsonObject.getString("uid"));
                        if (ObjectUtil.isNotEmpty(user)) {
                            ncgWatch.setUName(ObjectUtil.isNotEmpty(user.getUsername()) ? user.getUsername() : user.getNickName());
                        }
                    }
                }
            }
            return Result.success(ncgWatchVO);
        } else if (ObjectUtil.equals(type, 3)) {
            QueryWrapper<Receive> wrapper = new QueryWrapper<Receive>()
                    .in(CollectionUtils.isNotEmpty(iemi), "devSN", iemi)
                    .between(ObjectUtil.isNotEmpty(startTime) && ObjectUtil.isNotEmpty(endTime), "createtime", startTime, endTime)
                    .eq("deviceType", deviceType);
            List<Receive> receives = receiveService.list(wrapper);
            for (JSONObject jsonObject : imeiList) {
                SysUserEntity user = userService.getRedisByUid(jsonObject.getString("uid"));
                for (Receive receive : receives) {
                    if (ObjectUtil.equals(jsonObject.get("imei"), receive.getDevSN())) {
                        if (ObjectUtil.isNotEmpty(user)) {
                            receive.setUName(ObjectUtil.isNotEmpty(user.getUsername()) ? user.getUsername() : user.getNickName());
                        }
                    }
                }
            }
            return Result.success(receives);
        } else if (ObjectUtil.equals(type, 2)) {
            List<Saihong> saihongs = new ArrayList<>();
            for (String deviceMac : iemi) {
                // 设置请求体
                Map<String, Object> params = new HashMap<>();
                params.put("deviceMac", deviceMac);
                params.put("starttime", startTime);
                params.put("endtime", endTime);
                String param = JSON.toJSONString(params);
                String res = HttpUtils.sendPost("http://taiyibp.tjtzkt.com/getBpDatas.aspx", param);
                // 从json中获取data对应的数据

                List<Object> data;
                if (ObjectUtil.isNotEmpty(JSONObject.parseObject(res))) {
                    data = (List<Object>) JSONObject.parseObject(res).get("data");
                    for (int i = 0; i < data.size(); i++) {
                        Saihong saihong = new Saihong();
                        BeanUtil.copyProperties(data.get(i), saihong);
                        saihongs.add(saihong);
                    }
                }
            }
            for (Saihong saihong : saihongs) {
                for (JSONObject jsonObject : imeiList) {
                    if (ObjectUtil.equals(jsonObject.get("imei"), saihong.getDeviceNo())) {
                        SysUserEntity user = userService.getRedisByUid(jsonObject.getString("uid"));
                        if (ObjectUtil.isNotEmpty(user)) {
                            saihong.setUName(ObjectUtil.isNotEmpty(user.getUsername()) ? user.getUsername() : user.getNickName());
                        }
                    }
                }
            }
            return Result.success(saihongs);
        }
        return Result.error(Constants.CODE_500, "设备类型错误!!");
    }

    @GetMapping("/getDoctorDevice")
    public Result getDoctorDevice(@RequestParam Integer pageNum,
                                  @RequestParam Integer pageSize,
                                  @RequestParam(required = false, defaultValue = "") Long id,
                                  @RequestParam(required = false, defaultValue = "") String imei) {

        QueryWrapper<NcgDeviceWatch> wrapper = new QueryWrapper<NcgDeviceWatch>().eq("doctorid", id).like(ObjectUtil.isNotEmpty(imei), "imei", imei);

        return Result.success(ncgDeviceWatchService.page(new Page<>(pageNum, pageSize), wrapper));
    }

}

